<template>
    <div class="w100h80">
        <div class="navbar">
            <div class="contain">
                <n-button>Omega编程</n-button>
                <div class="menu">
                    <div class="menuitem" :class="cur == index ? 'active' : ''" @click="handle(item, index)"
                        v-for="(item, index) in menu">{{ item.name }}</div>
                </div>
                <n-button circle class="mauto" @click="search()">
                    <template #icon>
                        <n-icon>
                            <SearchIcon />
                        </n-icon>
                    </template>
                </n-button>
                <n-button v-if="info == null || info == ''" @click="login()" secondary strong>登录</n-button>
                <n-dropdown v-if="info != null && info != ''" trigger="hover" :options="options" @select="handleSelect">
                    <n-avatar size="small" :src="info.avatar" />
                </n-dropdown>
            </div>
        </div>
        <n-drawer v-model:show="active" :width="502" :placement="placement">
            <n-drawer-content title="搜索">
                <div class="dcontent">
                    <n-input placeholder="请输入" style="width: 50%;" v-model:value="keyword" @input="input"></n-input>
                    <nuxt-link :to="{
                        path: '/search', query: {
                            keyword: keyword
                        },
                        replace: true
                    }"><n-button @click="searchs()">搜索</n-button></nuxt-link>
                </div>
            </n-drawer-content>
        </n-drawer>
        <n-dialog-provider>
            <content />
        </n-dialog-provider>
    </div>
</template>
<script setup>
import { NButton, NDropdown, NIcon, NAvatar, NDrawer, NDrawerContent, NInput, useDialog, NDialogProvider, createDiscreteApi, NSpace, NText } from 'naive-ui';
import { LogIn, Search as SearchIcon } from '@vicons/ionicons5'
import { quarterArray } from 'naive-ui/es/date-picker/src/utils';
import { getCurrentInstance } from "vue";
import { useRouter } from 'nuxt/app';
let { ctx: that, proxy } = getCurrentInstance()
const router = useRouter();
onMounted(() => {
    getactivemenu()
    getinfo()
})
const forgetObj = ref(null);
const options = [{
    label: "用户中心",
    key: "profile"
}, {
    label: "退出",
    key: "exit"
},];
const cur = ref(0)
const keyword = ref("");
const active = ref(false);
const placement = ref("top");
const menu = ref([{
    name: "首页",
    path: "/"
}, {
    name: "拼团",
    path: "/pt"
}, {
    name: "直播",
    path: "/zb"
}, {
    name: "专栏",
    path: "/zl"
}, {
    name: "电子书",
    path: "/dzs"
},  {
    name: "课程",
    path: "/kc"
},

],)
const info = ref(null);
const phoneObj = ref(null);
const registerobj = ref(null);
const phoneform = ref({
    phone: "",
    code: ""
})
const buttonname = ref("获取验证码");
const handleSelect = (e) => {
    console.log(e)
    const { message, dialog } = createDiscreteApi(['message', 'dialog'])

    if (e == 'profile') {
        if (info.value.phone == null) {
            phoneObj.value = dialog.warning({
                title: '绑定手机号',
                content: () => h(NSpace, {
                    vertical: true
                }, [
                    h(NInput, {
                        defaultValue: "", placeholder: "请输入手机号",
                        onChange: (value) => {
                            phoneform.value.phone = value
                        }
                    }),
                    h(NSpace, {
                        vertical: false,

                    }, [
                        h(NInput, {
                            class: "w_60",

                            defaultValue: "", placeholder: "请输入验证码",
                            onChange: (value) => {
                                phoneform.value.code = value
                            }

                        }),
                        h(NButton, {
                            type: "success",
                            disabled: buttonname.value == "获取验证码" ? false : true,

                            onClick: async () => {
                                const regex = /^1[3456789]\d{9}$/;
                                if (phoneform.value.phone == '') {
                                    message.warning("请输入手机号");
                                    return
                                }
                                console.log(regex.test(phoneform.value.phone), "regex.test(phoneform.value.phone)")
                                if (!regex.test(phoneform.value.phone)) {
                                    message.warning("手机号格式不正确");
                                    return

                                }
                                const { data } = await useHttp("", "/get_captcha", {
                                    method: "POST",
                                    body: {
                                        phone: phoneform.value.phone
                                    }
                                })
                                console.log(data.value);
                                // tologin()
                                let count = 60;

                                let timer = setInterval(() => {
                                    count--;
                                    buttonname.value = count + 's';
                                    if (count == 0) {
                                        clearInterval(timer);
                                        buttonname.value = "获取验证码"
                                    }
                                }, 1000)
                            }
                        }, { default: () => buttonname.value })
                    ]),
                    h(NButton, {
                        type: "success",
                        class: "w_100",
                        onClick: () => {
                            console.log(username.value, password.value);
                            if (phoneform.value.phone == '' || phoneform.value.code == '') {
                                message.warning("请输入必填项");
                            } else {
                                tobdyzm()

                            }
                        }
                    }, { default: () => "确认" })
                ])
            })
        } else {
            router.push({
                path: "/yhzx",
            })
        }
    } else {
        dialog.warning({
            title: '警告',
            content: '是否确认退出登录？',
            positiveText: '确定',
            negativeText: '取消',
            draggable: true,
            onPositiveClick: async () => {
                message.success('确定')
                const { data } = useHttp("", "/logout", {
                    method: "post"
                });
                window.localStorage.clear();
                info.value = null
                that.$forceUpdate()
                // getinfo();

            },
            onNegativeClick: () => {

            }
        })
    }


}
const form = ref({
    username: "",
    password: ""
});
const username = ref("");
const password = ref("");
let dialogobj = ref(null)
const tobdyzm = async () => {
    const { message } = createDiscreteApi(['message'])
    const { data, error } = await useHttp("", "/bind_mobile", {
        method: "POST",
        body: {
            phone: phoneform.value.phone,
            code: phoneform.value.code
        }
    })
    console.log(data.value, message, error)
    if (data.value == undefined) {
        console.log("12333")
        message.warning(error.value.data.data);
    } else {
        message.success("绑定成功");
        phoneObj.value.destroy()

        getinfo()
    }
}
const login = () => {
    const { message, dialog, notification, loadingBar } = createDiscreteApi(['message', 'dialog', 'notification', 'loadingBar'])
    dialogobj.value = dialog.warning({
        title: '登录',
        content: () => h(NSpace, {
            vertical: true
        }, [
            h(NInput, {
                defaultValue: "", placeholder: "请输入用户名",
                onChange: (value) => {
                    form.value.username = value
                }
            }),
            h(NInput, {
                type: "password",
                defaultValue: "",
                placeholder: "请输入密码",
                onChange: (value) => {
                    form.value.password = value
                }
            }),
            h(NSpace, {
                vertical: false,
                justify: "space-between"
            }, [
                h(NText, {
                    class: "cur_point",
                    onClick: () => {
                        console.log("zhuce ")
                        toregister()
                        dialogobj.value.destroy()
                    }

                }, { default: () => "注册" }),
                h(NText, {

                    class: "cur_point",
                    onClick: () => {
                        console.log("zhuce ")
                        tofoget()
                        dialogobj.value.destroy()
                    }
                }, { default: () => "忘记密码" })
            ]),
            h(NButton, {
                type: "success",
                class: "w_100",
                onClick: () => {
                    console.log(username.value, password.value);
                    tologin()
                }
            }, { default: () => "登录" })
        ]
        ),
    })
}
const getinfo = async () => {
    const token = window.localStorage.getItem("token");
    const { data } = await useHttp("", "/getinfo");
    console.log(data)
    info.value = data.value
    console.log(info.value)

}
const tologin = async () => {
    const { message, dialog } = createDiscreteApi(['message', 'dialog'])
    if (form.value.username == '' || form.value.password == '') {
        message.warning("请输入必填项");

    }
    const { data, error } = await useHttp("", "/login", {
        method: "POST",
        body: {
            username: form.value.username,
            password: form.value.password
        }
    })
    console.log(data.value, message, error)
    if (data.value == undefined) {
        console.log("12333")
        message.warning(error.value.data.data);
    } else {
        message.success("登录成功");
        dialogobj.value.destroy()
        window.localStorage.setItem("token", data.value.token);
        // window.location.reload()
        that.$forceUpdate()
        getinfo()



    }

}
const search = () => {
    active.value = true;


}
const forgetform = ref({
    phone: "",
    code: "",
    password: "",
    repassword: ""
})

const tofoget = () => {
    const { message, dialog } = createDiscreteApi(['message', 'dialog'])
    forgetObj.value = dialog.warning({
        title: "重置密码",
        content: () => h(NSpace, {
            vertical: true
        }, [
            h(NInput, {
                defaultValue: "", placeholder: "请输入手机号",
                onChange: (value) => {
                    forgetform.value.phone = value
                }
            }),
            h(NSpace, {
                vertical: false,

            }, [
                h(NInput, {
                    class: "w_60",

                    defaultValue: "", placeholder: "请输入验证码",
                    onChange: (value) => {
                        forgetform.value.code = value
                    }

                }),
                h(NButton, {
                    type: "success",
                    disabled: buttonname.value == "获取验证码" ? false : true,

                    onClick: async () => {
                        const regex = /^1[3456789]\d{9}$/;
                        if (forgetform.value.phone == '') {
                            message.warning("请输入手机号");
                            return
                        }
                        console.log(regex.test(forgetform.value.phone), "regex.test(phoneform.value.phone)")
                        if (!regex.test(forgetform.value.phone)) {
                            message.warning("手机号格式不正确");
                            return

                        }
                        const { data } = await useHttp("", "/get_captcha", {
                            method: "POST",
                            body: {
                                phone: forgetform.value.phone
                            }
                        })
                        console.log(data.value);
                        // tologin()
                        let count = 60;

                        let timer = setInterval(() => {
                            count--;
                            buttonname.value = count + 's';
                            if (count == 0) {
                                clearInterval(timer);
                                buttonname.value = "获取验证码"
                            }
                        }, 1000)
                    }
                }, { default: () => buttonname.value })
            ]),
            h(NInput, {
                type: "password",
                defaultValue: "",
                placeholder: "请输入密码",
                onChange: (value) => {
                    forgetform.value.password = value
                }
            }),
            h(NInput, {
                type: "password",
                defaultValue: "",
                placeholder: "请输入确认密码",
                onChange: (value) => {
                    forgetform.value.repassword = value
                }
            }),
            h(NSpace, {
                vertical: false,
                justify: "space-between"
            }, [
                h(NText, {
                    class: "cur_point",
                    onClick: () => {
                        console.log("zhuce ")

                        forgetObj.value.destroy()
                        login()
                    }

                }, { default: () => "登录" }),

            ]),
            h(NButton, {
                type: "success",
                class: "w_100",
                onClick: () => {
                    console.log(username.value, password.value);
                    gotofoget()
                }
            }, { default: () => "重置密码" })
        ]
        ),
    })
}
const gotofoget = async () => {
    const { message } = createDiscreteApi(['message'])
    if (forgetform.value.password == '' || forgetform.value.repassword == '' || forgetform.value.phone == '' || forgetform.value.code == '') {
        message.warning("请输入必填项");
        return
    }
    if (forgetform.value.password !== forgetform.value.repassword) {
        message.warning("两次输入密码不一致");
        return
    }


    const { data, error } = await useHttp("", "/forget", {
        body: forgetform.value,
        method: "post"
    })

    if (data.value == undefined) {
        // setTimeout(() => {
        //     console.log(error)
        // }, 100)
        // console.log("12333")
        message.warning(error.value.data.data);
    } else {
        message.success("修改成功");
        forgetObj.value.destroy();




    }

}
const registerform = ref({
    username: "",
    password: "",
    repassword: ""
});
const toregister = () => {
    const { message, dialog } = createDiscreteApi(['message', 'dialog'])
    registerobj.value = dialog.warning({
        title: "注册",
        content: () => h(NSpace, {
            vertical: true
        }, [
            h(NInput, {
                defaultValue: "", placeholder: "请输入用户名",
                onChange: (value) => {
                    registerform.value.username = value
                }
            }),
            h(NInput, {
                type: "password",
                defaultValue: "",
                placeholder: "请输入密码",
                onChange: (value) => {
                    registerform.value.password = value
                }
            }),
            h(NInput, {
                type: "password",
                defaultValue: "",
                placeholder: "请输入确认密码",
                onChange: (value) => {
                    registerform.value.repassword = value
                }
            }),
            h(NSpace, {
                vertical: false,
                justify: "space-between"
            }, [
                h(NText, {
                    class: "cur_point",
                    onClick: () => {
                        console.log("zhuce ")

                        registerobj.value.destroy()
                        login()
                    }

                }, { default: () => "登录" }),

            ]),
            h(NButton, {
                type: "success",
                class: "w_100",
                onClick: () => {
                    console.log(username.value, password.value);
                    gotoregister()
                }
            }, { default: () => "注册" })
        ]
        ),
    })
}
const input = (e) => {
    console.log(e)
}
const searchs = () => {
    active.value = false;
    console.log(keyword.value)

}
const gotoregister = async () => {

    const { message } = createDiscreteApi(['message'])
    if (registerform.value.password == '' || registerform.value.repassword == '' || registerform.value.username == '') {
        message.warning("请输入必填项");
        return
    }
    if (registerform.value.password !== registerform.value.repassword) {
        message.warning("两次输入密码不一致");
        return
    }


    const { data, error } = await useHttp("", "/reg", {
        body: registerform.value,
        method: "post"
    })

    if (data.value == undefined) {
        // setTimeout(() => {
        //     console.log(error)
        // }, 100)
        // console.log("12333")
        message.warning(error.value.data.data);
    } else {
        message.success("注册成功");
        registerobj.value.destroy();




    }




}
// const searchym=()=>{
//     this.$router.push({
//         path:"/searchym"
//     })
// }
const handle = (item, index) => {
    navigateTo(item.path)
    cur.value = index
}
const route = useRoute();
const getactivemenu = () => {

    console.log(route.path, "router")
    menu.value.forEach((el, index) => {
        if (el.path == route.path || el.path.includes(route.path)) {
            cur.value = index
        }
    })
}

</script>
<style scoped>
.menu {
    display: flex;
    align-items: center;
    padding-left: 1rem;
    padding-right: 1rem;
}

.menuitem {
    padding: 0.25rem 0.5rem;
    cursor: pointer;
    margin-left: 0.25rem;
    margin-right: 0.25rem;
    border-radius: 5px;
}

.menuitem:hover {
    background: rgba(219, 234, 254, 1) !important;
    color: rgba(37, 99, 235, 1);
}

.active {
    background: rgba(219, 234, 254, 1) !important;
    color: rgba(37, 99, 235, 1);
}

.contain {
    display: flex;
    align-items: center;
    max-width: 1536px;
    width: 100%;
    margin: 0 auto;

}

.navbar {

    background: white;
    position: fixed;
    z-index: 1000;
    top: 0px;
    left: 0px;
    right: 0px;
    height: 60px;
    display: flex;
    align-items: center;

}

.w100h80 {
    width: 100%;
    height: 80px;
}

.mauto {
    margin-left: auto;
}

.dcontent {
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
}
</style>
<style>
.w_100 {
    width: 100%;

}

.w_60 {
    width: 60%;

}

.cur_point {
    cursor: pointer;
}
</style>